package com.heima.search.service.impl;

import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.HistorySearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @Author Lijx
 * @Date 2024-07-30 10:45
 */
@Service
public class HistorySearchServiceImpl implements HistorySearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索的关键词
     * @param searchWords
     * @param userId
     */
    @Async //异步方法
    public void saveSearchWords(String searchWords, Integer userId) {

        //校验搜索关键字是否是空字符串
        if (searchWords == null || searchWords.equals("")) {
            return;
        }

        //判断是否是游客登录
        if (userId == null || userId == 0) {
            return ;
        }

        //1.先查询当前用户对本次搜索词之前有役有搜过
        ApUserSearch keyword = mongoTemplate.findOne(
                Query.query(Criteria.where("keyword").is(searchWords).and("userId").is(userId)),
                ApUserSearch.class);

        //2.有:将该记录的时间更新为当前时间即可
        if (keyword != null) {
            keyword.setCreatedTime(new Date());
            mongoTemplate.save(keyword); //更新
        } else {
            //3.没有:判断当前用户搜索记录总量是否超过10
            List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                            .with(Sort.by(Sort.Direction.ASC, "createdTime")),
                    ApUserSearch.class);
            if (searchList != null && searchList.size() >= 10) {
                //4.超过10:将最旧的记录删除，并保存本次记录
                mongoTemplate.remove(searchList.get(0));
            }
            //5.没有超过:直接保存本次记录即可
            ApUserSearch apUserSearch = new ApUserSearch();
            apUserSearch.setUserId(userId);
            apUserSearch.setKeyword(searchWords);
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
        }

    }

    /**
     * 加载搜索记录列表
     * @return
     */
    @Override
    public ResponseResult searchWords() {
        //获取当前登录的用户id
        Integer userId = ApThreadLocalUtil.getUserId();

        //判断是否是游客登录
        if (userId == null || userId == 0) {
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        List<ApUserSearch> searchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                        .with(Sort.by(Sort.Direction.DESC,"createdTime")),
                ApUserSearch.class);
        return ResponseResult.okResult(searchList);
    }

    /**
     * 删除搜索记录
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteHistoryWords(String id) {
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserSearch apUserSearch = new ApUserSearch();
        apUserSearch.setId(id);
        //删除搜索记录
        mongoTemplate.remove(apUserSearch);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
